package com.jiyinit.web.core.activiti.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.activiti.cmd.HistoryProcessInstanceDiagramCmd;
import com.jiyinit.web.core.activiti.dto.*;
import com.jiyinit.web.core.activiti.entity.TabLeaveBillInfoEntity;
import com.jiyinit.web.core.activiti.entity.TabLeaveDealMindEntity;
import com.jiyinit.web.core.activiti.entity.TabUserMemershipEntity;
import com.jiyinit.web.core.activiti.enums.LeaveTypeEnum;
import com.jiyinit.web.core.activiti.enums.LeaveUserTaskEnum;
import com.jiyinit.web.core.activiti.enums.ProcessFlowEnum;
import com.jiyinit.web.core.activiti.service.*;
import com.jiyinit.web.core.activiti.util.MapToEntity;
import com.jiyinit.web.core.activiti.vo.NeedDealTaskEntity;
import com.jiyinit.web.core.activiti.vo.TabImMessageEntity;
import com.jiyinit.web.core.activiti.vo.TabLeaveBillinfoVo;
import com.jiyinit.web.core.activiti.vo.UnReadInfos;
import com.jiyinit.web.core.business.dto.MChatRequest;
import com.jiyinit.web.core.business.entity.*;
import com.jiyinit.web.core.business.service.*;
import com.jiyinit.web.core.common.config.PropertyPlaceholderConfigurer;
import com.jiyinit.web.core.common.util.HttpClientUtil;
import com.jiyinit.web.core.common.util.UserUtil;
import com.jiyinit.web.core.common.vo.LoginUserVo;
import com.jiyinit.web.core.common.vo.MobileUserVo;
import com.jiyinit.web.core.mobile.controller.MobileFileUploadController;
import com.jiyinit.web.core.mobile.vo.LeaveVo;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p></p>
 * <p>请假流程控制类
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author jack zh
 * @version 1.0
 * @date 2018/7/17
 * @since 1.0
 */
@Controller
@RequestMapping("/mobile/leave")
public class LeaveController {


    private static Logger logger = LoggerFactory.getLogger(LeaveController.class);

    @Resource(name = "leaveBillInfoServiceImpl")
    private LeaveBillInfoServiceImpl leaveBillInfoService;

    @Resource(name = "leaveDealMindServiceImpl")
    private LeaveDealMindServiceImpl leaveDealMindService;

    @Resource(name = "core.dictItemServiceImpl")
    private DictItemServiceImpl dictItemService;

    //工作流相关
    @Resource(name = "runtimeService")
    RuntimeService runtimeservice;
    @Resource(name = "identityService")
    IdentityService identityservice;
    @Resource(name = "taskService")
    TaskService taskservice;
    @Resource(name = "processEngine")
    ProcessEngine processEngine;

    @Resource(name = "leaveDealServiceImpl")
    private LeaveDealServiceImpl leaveDealService;

    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;

    @Resource(name = "core.orgServiceImpl")
    OrgServiceImpl orgService;

    @Resource(name = "userMemershipServiceImpl")
    private UserMemershipServiceImpl userMemershipService;

    @Resource(name = "core.taskServiceImpl")
    private TaskServiceImpl taskService;

    @Resource(name = "core.friendServiceImpl")
    private UserFriendServiceImpl userFriendService;

    @Resource(name = "core.userGroupServiceImpl")
    private UserGroupServiceImpl userGroupService;


    /**
     * 发起请假：【保存包括更新】 逻辑接口
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "saveLeave")
//,consumes="application/json", produces="application/json"
    public ResponseEntity<ResponseDto> saveLeave(HttpServletRequest request, @RequestParam String request_json) {
        String logJson = request.getParameter("request_json");
        LogUtil.info(logger, "接口参数:{}", logJson);

        TabLeaveBillInfoRequest billRequest = new TabLeaveBillInfoRequest();
        try {
            if (!Check.isNullStrStrict(logJson)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Map map = JsonEntityTransform.json2Map(logJson);
                String id = (String) map.get("id");
                String startTime = (String) map.get("lvStartTime");
                String endTime = (String) map.get("lvEndTime");
                String lvType = (String) map.get("lvType");
                String linkTel = (String) map.get("linkTel");
                String bakTel = (String) map.get("bakTel");
                Integer lvDay = (Integer) map.get("lvDay");
                Integer lvHours = (Integer) map.get("lvHours");
                String lvReason = (String) map.get("lvReason");
                String muuid = (String) map.get("mobileuuid");
                DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
                Date start =dateFormat.parse(startTime);
                Date end =dateFormat.parse(endTime);

                if (Check.isNullStr(lvType)) {
                    return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("请假类型不能为空"), HttpStatus.OK);
                } else if (Check.isNullStr(endTime)) {
                    return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("请假结束时间不能为空"), HttpStatus.OK);
                } else if (Check.isNullStr(startTime)) {
                    return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("请假开始不能为空"), HttpStatus.OK);
                } else if (Check.isNullStr(linkTel)) {
                    return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("联系电话不能为空"), HttpStatus.OK);
                } else if (Check.isNullObj(lvHours)) {
                    return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("请假时长不能为空"), HttpStatus.OK);
                } else if(lvReason.length()>200){
                    return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("请假理由应小于200字"), HttpStatus.OK);
                } else if(start.getTime()>end.getTime()){
                    return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("结束时间不能小于开始时间"), HttpStatus.OK);
                } else
                 {
                    if (!Check.isNullStr(id)) {
                        billRequest.setId(Integer.valueOf(id));
                    } else {
                        billRequest.setId(null);
                    }
                    billRequest.setLvType(lvType);
                    billRequest.setLvEndTime(sdf.parse(endTime));
                    billRequest.setLvStartTime(sdf.parse(startTime));
                    billRequest.setLinkTel(linkTel);
                    billRequest.setBakTel(bakTel);
                    billRequest.setLvDay(Double.valueOf(lvDay));
                    billRequest.setLvHours(Double.valueOf(lvHours));
                    billRequest.setLvReason(lvReason);
                    billRequest.setMobileuuid(muuid);
                }
            } else {
                return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("必传信息为空"), HttpStatus.OK);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);
        MobileUserVo vo = UserUtil.getMobileUser(loginUserVo.getToken());//根据token 用户id 获取用户所在部门信息（从session中取）

        TabLeaveBillInfoEntity record = new TabLeaveBillInfoEntity();
        BeanUtils.copyProperties(billRequest, record);
        record.setUserId(loginUserVo.getUserId());    //以session中的存储为准
        record.setOrgId(vo.getOrgId());     //以session中的存储为准
        record.setUserLevel(vo.getLevel() + "");    //以session中的存储为准
        record.setCreateDate(new Date());  //创建时间
        record.setIsDelete("0");  //未删除
        record.setIsAgree(LeaveTypeEnum.WaitCommit.getCode());//将状态设置为未提交
        record.setMobileuuid(billRequest.getMobileuuid());

        HashMap<String, Object> result = new HashMap<String, Object>();
        int num = 0;
        if (Check.isNullObj(billRequest.getId())) {
            synchronized (this) {
                leaveBillInfoService.insert(record);
                int maxId = leaveBillInfoService.getMaxIdByUserId(record.getUserId());
                result.put("saveBean", record);
                result.put("key", maxId);
            }
        } else {
            num = leaveBillInfoService.updateByPrimaryKeySelective(record);
            if (num > 0) {
                result.put("saveBean", record);
                result.put("key", record.getId());
            } else {
                return new ResponseEntity<>(ResponseDto.responseFail("更新失败"), HttpStatus.OK);
            }
        }

        return new ResponseEntity<>(ResponseDto.responseOK(result), HttpStatus.OK);
    }


    /**
     * 发起请假：【请假类型】 逻辑接口
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "getLeaveType{dictCode}", consumes = "application/json", produces = "application/json")
    public ResponseEntity<ResponseDto> getLeaveType(HttpServletRequest request, @PathVariable("dictCode") String dictCode, @RequestParam String request_json) {
        String logJson = request.getParameter("request_json");
        LogUtil.info(logger, "接口参数:{}", logJson);
        List<TabCoreDictItemEntity> itemList = dictItemService.selectByDictCode(dictCode);

        return new ResponseEntity<>(ResponseDto.responseOK(itemList), HttpStatus.OK);
    }

    /**
     * 发起请假：【开始请假】 逻辑接口
     *
     * @param request （只穿 id ，mobileUuid 即可）
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "startLeave")
//,consumes="application/json", produces="application/json"
    public ResponseEntity<ResponseDto> startLeave(HttpServletRequest request, @RequestParam String request_json) {
        String logJson = request.getParameter("request_json");
        LogUtil.info(logger, "接口参数:{}", logJson);
        TabLeaveBillInfoRequest billRequest = new TabLeaveBillInfoRequest();
        LoginUserVo loginUserVo = null;
        if (!Check.isNullStrStrict(logJson)) {
            try {
                loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Map map = JsonEntityTransform.json2Map(logJson);
                String id = (String) map.get("id");
                //String muuid = (String) map.get("mobileuuid");

                billRequest.setId(Integer.valueOf(id));
                //billRequest.setMobileuuid(muuid);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail(""), HttpStatus.OK);
        }

        //接收信息
        //判断客户端标识是否存在【必填项】
        if (billRequest.getId() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("请假单主键不可以为空"), HttpStatus.OK);
        }
        //判断客户端标识是否存在【必填项】
        /*if(billRequest.getMobileuuid()==null||"".equals(billRequest.getMobileuuid())){
            return new ResponseEntity<>(ResponseDto.responseFail("客户端唯一标识不能为空"), HttpStatus.OK);
        }*/
        //查询订单信息 存在才能开始请假工作流
        TabLeaveBillInfoEntity record = new TabLeaveBillInfoEntity();
        record.setId(billRequest.getId());   //主键
        //record.setMobileuuid(billRequest.getMobileuuid()); //客户端唯一标识
        record.setIsDelete("0");  //未删除
        List<TabLeaveBillInfoEntity> livelist = leaveBillInfoService.findBySelective(record);
        if(livelist.get(0).getLvReason().length()>200){
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("请假理由应小于200字"), HttpStatus.OK);
        }
        if (livelist.size() > 0) {
            TabLeaveBillInfoEntity billBean = livelist.get(0);
            billBean.setIsAgree(LeaveTypeEnum.WaitReview.getCode());//提交时将状态设置为待审批
            //开启请假流程
            //1.启动一个实例（先判断实例是否启动）
            if (null != billBean.getExecutionId()) {
                if (!("".equals(billBean.getExecutionId().trim())))
                    return new ResponseEntity<>(ResponseDto.responseFail("订单已经提交，禁止重复提交"), HttpStatus.OK);
            }

            MobileUserVo vo = UserUtil.getMobileUser(loginUserVo.getToken());
            ProcessInstance processInstance = leaveBillInfoService.startWorkflow(billBean, "" + loginUserVo.getUserId());


            //2.完成当前任务。
            List<Task> list = taskservice.createTaskQuery().taskAssignee("" + vo.getUserId()).processInstanceId(processInstance.getId()).executionId(processInstance.getId()).orderByTaskCreateTime().asc().list();//使用创建时间的升序排列
            for (Task task : list) {
                logger.info("--------" + task.getAssignee() + "任务:" + task.getName() + "-----------------");
                logger.info("任务ID:" + task.getId());
                logger.info("任务名称:" + task.getName());
                logger.info("任务的创建时间:" + task.getCreateTime());
                logger.info("任务的办理人:" + task.getAssignee());
                logger.info("流程实例ID：" + task.getProcessInstanceId());
                logger.info("执行对象ID:" + task.getExecutionId());
                logger.info("流程定义ID:" + task.getProcessDefinitionId());
                if (task.getTaskDefinitionKey().trim().equals(LeaveUserTaskEnum.usertask_3.getCode()))  //只有当时提出申请节点时 才自动拾取并提交
                {
                    taskservice.complete(task.getId()); //完成
                    //保存处理意见
                    TabLeaveDealMindEntity mindEntity = new TabLeaveDealMindEntity();

                    mindEntity.setTaskName(task.getName());
                    mindEntity.setTaskId(task.getId());
                    mindEntity.setCreateDate(new Date());
                    mindEntity.setDealUserid(vo.getUserId());
                    mindEntity.setStatus("1");  //有效
                    mindEntity.setIsAgree("1");  //同意
                    mindEntity.setDealMindInfo("提交请假申请");
                    leaveDealMindService.insertSelective(mindEntity);
                }

            }


            return new ResponseEntity<>(ResponseDto.responseOK("流程启动成功"), HttpStatus.OK);

        } else {
            return new ResponseEntity<>(ResponseDto.responseFail("请先保存请假单"), HttpStatus.OK);
        }
    }

    /**
     * 发起请假：【查询请假记录】 逻辑接口
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "listLeaveInfo", consumes = "application/json", produces = "application/json")
    public PagingResult listLeaveInfo(HttpServletRequest request, LeaveBillRequset billRequset, @RequestParam String request_json) {
        String logJson = request.getParameter("request_json");
        LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);
        LogUtil.info(logger, "接口参数:{}", logJson);

        billRequset.setUserId(loginUserVo.getUserId());
        billRequset.setLimit(10);
        PagingResult pagingResult = leaveBillInfoService.getUserInfoListByCondiction(billRequset);
        LogUtil.info(logger, "getTotalRecords:{},getTotalPages:{},getRows:{}", pagingResult.getTotalRecords(), pagingResult.getTotalPages(), pagingResult.getRows());
        return pagingResult;
    }


    /**
     * 发起请假：【查询修改记录详情】 逻辑接口
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "preBillModify")
//,consumes="application/json", produces="application/json"
    public ResponseEntity<ResponseDto> preBillModify(HttpServletRequest request, @RequestParam String request_json) {
        String logJson = request.getParameter("request_json");
        LogUtil.info(logger, "接口参数:{}", logJson);
        TabLeaveBillInfoRequest billRequest = (TabLeaveBillInfoRequest) JsonEntityTransform.json2Object(logJson, TabLeaveBillInfoRequest.class);
        LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);
        //判断客户端标识是否存在【必填项】
        if (billRequest.getId() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("请假主键不可以为空"), HttpStatus.OK);
        }
        //判断客户端标识是否存在【必填项】
        if (billRequest.getMobileuuid() == null || "".equals(billRequest.getMobileuuid())) {
            return new ResponseEntity<>(ResponseDto.responseFail("客户端唯一标识不能为空"), HttpStatus.OK);
        }

        //查询订单信息 存在才能开始请假工作流
        TabLeaveBillInfoEntity record = new TabLeaveBillInfoEntity();
        record.setId(billRequest.getId());   //主键
        record.setMobileuuid(billRequest.getMobileuuid()); //客户端唯一标识
        record.setIsDelete("0");  //未删除
        record.setUserId(loginUserVo.getUserId());
        List<TabLeaveBillInfoEntity> livelist = leaveBillInfoService.findBySelective(record);
        if (livelist.size() > 0) {
            TabLeaveBillInfoEntity billBean = livelist.get(0);

            //请假详情
            if (null != billBean.getExecutionId()) {
                return new ResponseEntity<>(ResponseDto.responseFail("订单已经提交，信息不可修改"), HttpStatus.OK);
            }
            return new ResponseEntity<>(ResponseDto.responseOK(billBean), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(ResponseDto.responseFail("信息不存在"), HttpStatus.OK);
        }
    }

    /**
     * 查看正在进行中的流程图
     *
     * @param
     * @return
     * @author lishaochuan
     * @create 2017/5/5 11:09
     */
    @RequestMapping(value = "show{processInstId}")
    public void show(@PathVariable("processInstId") String processInstId, HttpServletResponse response, @RequestParam String request_json) throws Exception {
        Command<InputStream> cmd = new HistoryProcessInstanceDiagramCmd(processInstId);
        InputStream is = processEngine.getManagementService().executeCommand(cmd);
        response.setContentType("image/png");
        int len = 0;
        byte[] b = new byte[1024];
        while ((len = is.read(b, 0, 1024)) != -1) {
            response.getOutputStream().write(b, 0, len);
        }
        is.close();
    }

    /**
     * 查询我的请假接口
     *
     * @param request
     * @param request_json
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryMyLeaveS")
    public ResponseEntity<ResponseDto> queryMyLeaveS(HttpServletRequest request, @RequestParam String request_json) {
        String logJson = request.getParameter("request_json");
        //LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);
        Map map = JsonEntityTransform.json2Map(request_json);
        TabLeaveBillInfoEntity record = new TabLeaveBillInfoEntity();
        record.setUserId((Integer) map.get("userId"));
        String convertStatus = (String) map.get("convertStatus");
        if (!Check.isNullStr(convertStatus)) {
            logger.info("查询类型: {}", convertStatus);
            record.setIsAgree(convertStatus);
        }
        List<TabLeaveBillInfoEntity> livelist = leaveBillInfoService.findBySelective(record);
        for (TabLeaveBillInfoEntity obj : livelist) {
            String executionId = obj.getExecutionId();
            if (Check.isNullStr(executionId)) {
                obj.setCurrentUserName(null);
            } else {
                String currentUserName = getCurrentUserNameByExecutionId(executionId);
                obj.setCurrentUserName(currentUserName);
            }
        }
        return new ResponseEntity<>(ResponseDto.responseOK(livelist), HttpStatus.OK);
    }

    private void setTaskKey(List<TabLeaveBillInfoEntity> newlist, LoginUserVo loginUserVo) {
        for (int i = 0; i < newlist.size(); i++) {
            String executionId = newlist.get(i).getExecutionId();
            NeedDealTaskRequest dealTaskRequest = new NeedDealTaskRequest();
            dealTaskRequest.setUserId(loginUserVo.getUserId() + "");  //查询节点处理人代办清单

            List<Task> tasks = taskservice.createTaskQuery().processDefinitionKey(ProcessFlowEnum.Leave.getCode()).executionId(executionId).listPage((dealTaskRequest.getPage() - 1) * dealTaskRequest.getLimit(), dealTaskRequest.getLimit());

            if (!Check.isNullCollection(tasks)) {
                String taskDefinitionKey = tasks.get(tasks.size() - 1).getTaskDefinitionKey();
                newlist.get(i).setTaskDefinitionKey(taskDefinitionKey);
            } else {
                newlist.get(i).setTaskDefinitionKey(null);
            }
        }
    }

    /**
     * 查询下个环节的审批人
     *
     * @param request
     * @param request_json
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryReviewUsers")
    public ResponseEntity<ResponseDto> queryReviewUsers(HttpServletRequest request, @RequestParam String request_json) {
        JSONObject jsonObject = JSON.parseObject(request_json);
        String id = String.valueOf(jsonObject.get("id") + "");
        LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(request_json, LoginUserVo.class);
        Integer userId = loginUserVo.getUserId();

        List<TabCoreUserEntity> reviewUserList = new ArrayList<>();

        TabLeaveBillInfoEntity billEntity = new TabLeaveBillInfoEntity();
        billEntity.setId(Integer.valueOf(id));
        billEntity.setUserId(userId);
        List<TabLeaveBillInfoEntity> billList = leaveBillInfoService.findBySelective(billEntity);
        if (!Check.isNullCollection(billList)) {
            billEntity = billList.get(0);
            String taskKey = "";
            TabCoreUserEntity taskReviewUser = null;
            switch (billEntity.getUserLevel()) {
                case "1":
                    taskKey = LeaveUserTaskEnum.usertask_5.getCode();
                    billEntity.setTaskDefinitionKey(taskKey);
                    taskReviewUser = getTaskReviewUser(billEntity, false);
                    reviewUserList.add(taskReviewUser);
                    String LEAVE_DAYS = (String) PropertyPlaceholderConfigurer.getContextProperty("LEAVE_DAYS");
                    boolean b = isOverflowDay(billEntity.getLvDay(), billEntity.getLvHours(), LEAVE_DAYS);
                    if (!b) {
                        taskKey = LeaveUserTaskEnum.usertask_12.getCode();
                        billEntity.setTaskDefinitionKey(taskKey);
                        taskReviewUser = getTaskReviewUser(billEntity, true);
                        reviewUserList.add(taskReviewUser);
                    }
                    taskKey = LeaveUserTaskEnum.usertask_14.getCode();
                    billEntity.setTaskDefinitionKey(taskKey);
                    taskReviewUser = getTaskReviewUser(billEntity, true);
                    reviewUserList.add(taskReviewUser);
                    break;
                case "2":
                    taskKey = LeaveUserTaskEnum.usertask_12.getCode();
                    billEntity.setTaskDefinitionKey(taskKey);
                    taskReviewUser = getTaskReviewUser(billEntity, true);
                    reviewUserList.add(taskReviewUser);
                    taskKey = LeaveUserTaskEnum.usertask_14.getCode();
                    billEntity.setTaskDefinitionKey(taskKey);
                    taskReviewUser = getTaskReviewUser(billEntity, true);
                    reviewUserList.add(taskReviewUser);
                    break;
                case "3":
                    taskKey = LeaveUserTaskEnum.usertask_14.getCode();
                    billEntity.setTaskDefinitionKey(taskKey);
                    taskReviewUser = getTaskReviewUser(billEntity, true);
                    reviewUserList.add(taskReviewUser);
                    break;
                default:
                    break;
            }
        }
        return new ResponseEntity<>(ResponseDto.responseOK(reviewUserList), HttpStatus.OK);
    }

    /**
     * 根据任务key查询节点处理人
     *
     * @param billEntity
     * @return
     */
    private TabCoreUserEntity getTaskReviewUser(TabLeaveBillInfoEntity billEntity, boolean isTask12) {
        TabUserMemershipEntity shipEntity = new TabUserMemershipEntity();
        if (isTask12) {
            shipEntity.setOrgId(null);
        } else {
            shipEntity.setOrgId(billEntity.getOrgId());
        }
        shipEntity.setGroupKey(billEntity.getTaskDefinitionKey());
        shipEntity.setProcinstKey(ProcessFlowEnum.Leave.getCode());
        shipEntity.setIsDelete("0");  //未删除
        List<TabUserMemershipEntity> shipList = userMemershipService.findBySelective(shipEntity);
        String mainUserId = "";
        for (TabUserMemershipEntity shipBean : shipList) {
            if (shipBean.getIsMain().equals("1")) {
                mainUserId = shipBean.getUserId() + "";
            }
        }
        return getUserInfos(Integer.valueOf(mainUserId));
    }

    private boolean isOverflowDay(Double day, Double hours, String LEAVE_DAYS) {
        if (day > Integer.parseInt(LEAVE_DAYS)) {
            return false;
        } else if (day == Integer.parseInt(LEAVE_DAYS)) {
            if (hours > 0) {
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    /**
     * 查询是否有待审批任务
     *
     * @param request
     * @param request_json
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryWaitDoInfo")
    public ResponseEntity<ResponseDto> queryWaitDoInfo(HttpServletRequest request, @RequestParam String request_json) throws Exception {
        LogUtil.info(logger, "接口参数:{}", request_json);
        LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(request_json, LoginUserVo.class);

        NeedDealTaskRequest dealTaskRequest = new NeedDealTaskRequest();
        dealTaskRequest.setUserId(loginUserVo.getUserId() + "");  //查询节点处理人代办清单
        List<NeedDealTaskEntity> taskList = leaveDealService.getNeedDealTask(dealTaskRequest);
        Map<String, UnReadInfos> infos = new HashMap<String, UnReadInfos>();

        UnReadInfos info1 = new UnReadInfos();
        if (!Check.isNullCollection(taskList)) {
            info1.setHaveTasks("y");
            info1.setTaskNum(taskList.size());
        }
        infos.put("reviewTask", info1);

        JSON json = getChatHistoryMsg(request);
        String jsonString = json.toJSONString();
        Map<?, ?> map = JsonEntityTransform.json2Map(jsonString);
        LinkedHashMap pageResult = (LinkedHashMap) map.get("data");
        List<LinkedHashMap> rows = (List<LinkedHashMap>) pageResult.get("rows");
        int totalUnread = 0;
        UnReadInfos info2 = new UnReadInfos();
        if (!Check.isNullCollection(rows)) {
            for (LinkedHashMap obj : rows) {
                TabImMessageEntity entity = MapToEntity.mapToEntity(obj, TabImMessageEntity.class);
                String unreadCount = entity.getUnreadCount();
                if (!Check.isNullStrStrict(unreadCount)) {
                    totalUnread += Integer.valueOf(unreadCount);
                }
            }
            if (totalUnread > 0) {
                info2.setHaveTasks("y");
            }
            info2.setTaskNum(totalUnread);
        }

        infos.put("chatTask", info2);

        UnReadInfos info4 = new UnReadInfos();
        TabCoreTaskRequest coreTaskRequest = (TabCoreTaskRequest) JsonEntityTransform.json2Object(request_json, TabCoreTaskRequest.class);
        int topOrgId = coreTaskRequest.getTopOrgId();
        List<TabCoreOrgEntity> list = orgService.getChildOrgById(topOrgId);
        List<Integer> idList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            int orgId = list.get(i).getOrgId();
            idList.add(orgId);
        }
        TabCoreTask coreTask = taskService.findTaskIdByTaskCla(idList);
        info4.setTaskId(coreTask.getTaskId());
        info4.setCreateUid(coreTask.getCreateUid());
        infos.put("ExchangeGarden", info4);

        //好友申请未处理
        int friendCount = userFriendService.getFriendMsg(loginUserVo.getUserId());
        UnReadInfos info3 = new UnReadInfos();
        if (friendCount > 0) {
            info3.setHaveTasks("y");
            info3.setTaskNum(friendCount);
        }
        infos.put("friendTask", info3);

        //出差申请待审批
        EvectionRequest evectionRequest = (EvectionRequest) JsonEntityTransform.json2Object(request_json, EvectionRequest.class);
        List<Task> evectionEntities = taskservice.createTaskQuery().processDefinitionKey(ProcessFlowEnum.Evection.getCode()).taskCandidateOrAssigned(evectionRequest.getUserId() + "").listPage((evectionRequest.getPage() - 1) * evectionRequest.getLimit(), evectionRequest.getLimit());
        UnReadInfos info5 = new UnReadInfos();
        if (!Check.isNullCollection(evectionEntities)) {
            info5.setHaveTasks("y");
            info5.setTaskNum(evectionEntities.size());

            info1.setHaveTasks("y");
            int taskNum = info1.getTaskNum();
            info1.setTaskNum(taskNum + info5.getTaskNum());
        }
        infos.put("evectionTask", info5);

        logger.info("json", JsonEntityTransform.object2Json(infos));
        return new ResponseEntity<>(ResponseDto.responseOK(infos), HttpStatus.OK);
    }

    /**
     * 获取当前任务节点的办理人
     *
     * @param executionId
     * @return
     */
    private String getCurrentUserNameByExecutionId(String executionId) {
        Task task = taskservice.createTaskQuery().processDefinitionKey(ProcessFlowEnum.Leave.getCode()).executionId(executionId).singleResult();
        if (!Check.isNullObj(task)) {
            String assignee = task.getAssignee();
            TabCoreUserEntity userEntity = getUserInfos(Integer.valueOf(assignee));
            return userEntity.getUserName();
        }
        return "";
    }


    /**
     * 获取用户信息
     *
     * @param userId
     * @return
     */
    public TabCoreUserEntity getUserInfos(Integer userId) {
        return userService.getUserInfoByUserId(userId);
    }

    /**
     * 获取部门信息
     *
     * @param orgId
     * @return
     */
    public TabCoreOrgEntity getOrgInfos(Integer orgId) {
        return orgService.selectById(orgId);
    }

    public JSON getChatHistoryMsg(HttpServletRequest request) {
        String path = (String) PropertyPlaceholderConfigurer.getContextProperty("IM_URL");
        MChatRequest messageRequest = MobileFileUploadController.convertRequest(request, MChatRequest.class);
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("token", messageRequest.getToken());
        headers.put("sign", messageRequest.getSign());
        List<TabUserGroupEntity> group = userGroupService.findBySelective(messageRequest);//获取进群时间 群组id
        StringBuffer sbf = new StringBuffer();
        int size = group.size();
        for (int i = 0; i < size; i++) {
            TabUserGroupEntity entity = group.get(i);
            if (i == (size - 1)) {
                sbf.append(entity.getGroupId());
            } else {
                sbf.append(entity.getGroupId() + ",");
            }
        }
        messageRequest.setGroupIdstr(sbf.toString());
        String paramsStr = JsonEntityTransform.object2Json(messageRequest);
        String result = HttpClientUtil.post(path + "/msg/getChatHistoryMsg", paramsStr, headers);
        return JSON.parseObject(result);
    }

    /**
     * 查询当天请假人数
     *
     * @param req
     * @param request_json
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getLeaveInfo")
    public ResponseEntity<ResponseDto> getLeaveInfo(HttpServletRequest req, String request_json) {
        logger.info("传入参数: {}", request_json);
        LeaveBillRequset request = JsonEntityTransform.json2Object(request_json, LeaveBillRequset.class);
        logger.info("转换为obj之后的参数: {}", request.toString());

        String day = request.getDay();
        String year = request.getYear();
        String month = request.getMonth();

        if (request.getLevel() == 3) {
            request.setOrgId(null);

            int mon = getDaysByYearMonth(Integer.valueOf(year), Integer.valueOf(month));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
            month = Integer.valueOf(month) >= 10 ? month : "0" + month;
            List<LeaveVo> list = new ArrayList();

            for (int i = 1; i <= mon; i++) {
                day = i >= 10 ? i + "" : "0" + i;
                Date num = null;
                try {
                    num = sdf.parse(year + month + day + " 08:30:00");
                    request.setEra(num);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if(num != null ){
                    String dateStr = year + month + day;
                    HashMap<String, String> param = new HashMap<>();
                    param.put("date", dateStr);
                    String jsonStr = HttpClientUtil.get("http://api.goseek.cn/Tools/holiday", param, null);
                    Map<?, ?> map = JsonEntityTransform.json2Map(jsonStr);
                    jsonStr = String.valueOf(map.get("data"));
                    if (!"0".equals(jsonStr)){
                        LeaveVo leaveVo = new LeaveVo();
                        leaveVo.setNum("0");
                        leaveVo.setDate(i+"");
                        list.add(leaveVo);
                        continue;
                    }
                }
                PagingResult<TabLeaveBillinfoVo> pag = leaveBillInfoService.find(request);
                LeaveVo leaveVo = new LeaveVo();
                leaveVo.setNum(String.valueOf(pag.getRows().size()));
                leaveVo.setDate(i+"");
                list.add(leaveVo);
            }
            return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(list), HttpStatus.OK);

        } else if (request.getLevel() == 2) {

            int mon = getDaysByYearMonth(Integer.valueOf(year), Integer.valueOf(month));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
            month = Integer.valueOf(month) >= 10 ? month : "0" + month;
            List<LeaveVo> list = new ArrayList();

            for (int i = 1; i <= mon; i++) {
                day = i >= 10 ? i + "" : "0" + i;
                Date num = null;
                try {
                    num = sdf.parse(year + month + day + " 08:30:00");
                    request.setEra(num);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if(num != null ){
                    String dateStr = year + month + day;
                    HashMap<String, String> param = new HashMap<>();
                    param.put("date", dateStr);
                    String jsonStr = HttpClientUtil.get("http://api.goseek.cn/Tools/holiday", param, null);//判断节假日
                    Map<?, ?> map = JsonEntityTransform.json2Map(jsonStr);
                    jsonStr = String.valueOf(map.get("data"));
                    if (!"0".equals(jsonStr)){
                        LeaveVo leaveVo = new LeaveVo();
                        leaveVo.setNum("0");
                        leaveVo.setDate(i+"");
                        list.add(leaveVo);
                        continue;
                    }
                }
                PagingResult<TabLeaveBillinfoVo> pag = leaveBillInfoService.find(request);
                LeaveVo leaveVo = new LeaveVo();
                leaveVo.setNum(String.valueOf(pag.getRows().size()));
                leaveVo.setDate(i+"");
                list.add(leaveVo);
            }
            return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(list), HttpStatus.OK);

        }
        return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("没有权限"), HttpStatus.OK);
    }

    /**
     * 根据 年、月 获取对应的月份 的 天数
     */
    public static int getDaysByYearMonth(int year, int month) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }


    /**
     * 查询当天请假人数详情
     *
     * @param req
     * @param request_json
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getLeaveList")
    public ResponseEntity<ResponseDto> getLeaveList(HttpServletRequest req, String request_json) {
        logger.info("传入参数: {}", request_json);
        LeaveBillRequset request = JsonEntityTransform.json2Object(request_json, LeaveBillRequset.class);
        logger.info("转换为obj之后的参数: {}", request.toString());

        String day = request.getDay();
        String year = request.getYear();
        String month = request.getMonth();

        if (request.getLevel() == 3) {
            request.setOrgId(null);
            if (day != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
                month = Integer.valueOf(month) >= 10 ? month : "0" + month;
                day = Integer.valueOf(day) >= 10 ? day : "0" + day;
                Date num=null;
                try {
                    num = sdf.parse(year + month + day + " 08:30:00");
                    request.setEra(num);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if(num != null ){
                    String dateStr = year + month + day;
                    HashMap<String, String> param = new HashMap<>();
                    param.put("date", dateStr);
                    String jsonStr = HttpClientUtil.get("http://api.goseek.cn/Tools/holiday", param, null);//判断节假日
                    Map<?, ?> map = JsonEntityTransform.json2Map(jsonStr);
                    jsonStr = String.valueOf(map.get("data"));
                    if (!"0".equals(jsonStr)){
                        PagingResult<TabLeaveBillinfoVo> pag=new PagingResult<>();
                        return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(pag.getRows()), HttpStatus.OK);
                    }
                }

                PagingResult<TabLeaveBillinfoVo> pag = leaveBillInfoService.find(request);
                return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(pag.getRows()), HttpStatus.OK);
            }

        } else if (request.getLevel() == 2) {

            if (day != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
                month = Integer.valueOf(month) >= 10 ? month : "0" + month;
                day = Integer.valueOf(day) >= 10 ? day : "0" + day;
                Date num =null;
                try {
                    num = sdf.parse(year + month + day + " 08:30:00");
                    request.setEra(num);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if(num != null ){
                    String dateStr = year + month + day;
                    HashMap<String, String> param = new HashMap<>();
                    param.put("date", dateStr);
                    String jsonStr = HttpClientUtil.get("http://api.goseek.cn/Tools/holiday", param, null);//判断节假日
                    Map<?, ?> map = JsonEntityTransform.json2Map(jsonStr);
                    jsonStr = String.valueOf(map.get("data"));
                    if (!"0".equals(jsonStr)){
                        PagingResult<TabLeaveBillinfoVo> pag=new PagingResult<>();
                        return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(pag.getRows()), HttpStatus.OK);
                    }
                }
                PagingResult<TabLeaveBillinfoVo> pag = leaveBillInfoService.find(request);
                return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(pag.getRows()), HttpStatus.OK);
            }
        }
        return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("没有权限"), HttpStatus.OK);
    }

}
